package com.shuziren.interceptor;



import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class JWTTokenUtil {
    // 建议使用固定密钥（生产环境应从配置读取）
    private static final SecretKey KEY = Jwts.SIG.HS256.key().build();
    private static final long EXPIRATION = 7200000; // 2小时
    private static final Set<String> invalidTokens = new HashSet<>();

    public static String createToken(String account) {
        return Jwts.builder()
                .subject(account)
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(KEY)
                .compact();
    }

    public static String createToken(String account, Integer userId) {
        return Jwts.builder()
                .subject(account)
                .claim("userId", userId) // 添加用户ID到JWT的claims中
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(KEY)
                .compact();
    }

    public static String parseToken(String token) {
        return Jwts.parser()
                .verifyWith(KEY)
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .getSubject();
    }

    public static Integer getUserIdFromToken(String token) {
        return Jwts.parser()
                .verifyWith(KEY)
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .get("userId", Integer.class);
    }

    // 添加异常类型捕获
    public static boolean validateToken(String token) {
        try {
            if (invalidTokens.contains(token)) {
                return false;
            }
            Jwts.parser().verifyWith(KEY).build().parse(token);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }

    public static void invalidateToken(String token) {
        invalidTokens.add(token);
    }
}